package com.atguigu.gmall.user.controller;

import com.atguigu.gmall.common.constant.RedisConst;
import com.atguigu.gmall.common.result.Result;
import com.atguigu.gmall.common.util.AuthContextHolder;
import com.atguigu.gmall.model.order.OrderDetail;
import com.atguigu.gmall.model.order.OrderInfo;
import com.atguigu.gmall.model.user.UserAddress;
import com.atguigu.gmall.model.user.UserInfo;
import com.atguigu.gmall.user.service.UserInfoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/api/user/passport")
public class UserInfoApiController {
    @Autowired
    private UserInfoService userInfoService;
    @Autowired
    private RedisTemplate redisTemplate;
    //提交表单
    @PostMapping("/login")
    public Result login(@RequestBody UserInfo userInfo){
        //0:校验用户名密码不能为空  null 或是 ""  "   "   同学们完成了
        //1.校验用户名密码是否正确
        userInfo = userInfoService.login(userInfo);
        if (null != userInfo){
            //1.1:成功了
            //2:保存用户信息到Redis缓存中   前缀+token
            String token = UUID.randomUUID().toString();
            redisTemplate.opsForValue().set(RedisConst.USER_KEY_PREFIX + token,
                    userInfo.getId().toString(),RedisConst.USERKEY_TIMEOUT, TimeUnit.SECONDS);
            //3:发送令牌  昵称
            Map map = new HashMap();
            map.put("token",token);
            map.put("nickName",userInfo.getNickName());
            return Result.ok(map);
        }else {
            //1.2 失败了 显示错误信息
            return Result.fail().message("账户或者密码不正确");
        }
    }

    //获取收货地址
    @GetMapping("/getUserAddressList")
    public List<UserAddress> getUserAddressList(HttpServletRequest request){
        String userId = AuthContextHolder.getUserId(request);
        return userInfoService.getUserAddressList(userId);
    }


}
